#include "contactinfo.h"
#include "contactsmodel.h"

ContactsModel::ContactsModel(QObject *parent) :
    QAbstractListModel(parent)
{
}

ContactsModel::~ContactsModel()
{
    qDeleteAll(m_contacts);
}

ContactInfo * ContactsModel::addContact(const QString &id, const QString &networkId)
{
    ContactInfo * contact = new ContactInfo(id, networkId);

    beginInsertRows(QModelIndex(), m_contacts.count(), m_contacts.count());
    m_contacts.append(contact);
    endInsertRows();

    connect(contact, SIGNAL(changed(ContactInfo*)), this, SLOT(contactChanged(ContactInfo*)));
    return contact;
}

ContactInfo * ContactsModel::getContact(const QString &id, const QString &networkId) const
{
    foreach (ContactInfo * contact, m_contacts) {
        if (contact->id() == id && contact->networkId() == networkId)
            return contact;
    }
    return 0;
}

void ContactsModel::removeContact(ContactInfo * item)
{
}

int ContactsModel::rowCount(const QModelIndex &parent) const
{
    if (!parent.isValid())
        return m_contacts.count();
    else
        return 0;
}

void ContactsModel::contactChanged(ContactInfo *contact)
{
    int row = m_contacts.indexOf(contact);
    if (row != -1) {
        QModelIndex changed = index(row, 0, QModelIndex());
        emit dataChanged(changed, changed);
    }
}

QModelIndex ContactsModel::index(int row, int column, const QModelIndex &parent) const
{
    if (hasIndex(row, column, parent)) {
        if (!parent.isValid())
            return createIndex(row, column, m_contacts.at(row));
    }
    return QModelIndex();
}

QVariant ContactsModel::data(const QModelIndex &index, int role) const
{
    if (index.isValid()) {
        ContactInfo * item;

        item = static_cast<ContactInfo*>(index.internalPointer());
        switch (role) {
        case Qt::DisplayRole:
            return item->name();
        case Qt::ToolTipRole:
            return item->presenceText();
        case PictureRole:
            return item->picture();
        case PresenseRole:
            return item->presence();
        case UnreadMessagesRole:
            return 5;
        }
    }
    return QVariant();
}
